package com.zrb.mobile;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.zrb.mobile.adapter.model.PersonNumberDto;
import com.zrb.applib.utils.LocalUserInfo;
import com.zrb.mobile.register.UserRegister;
import com.zrb.mobile.register.User_phone_login;
import com.zrb.mobile.ucenter.User_my_attention;
import com.zrb.mobile.ucenter.User_my_collection;
import com.zrb.mobile.ucenter.User_my_dynamic;
import com.zrb.mobile.ucenter.User_my_ownprojects;
import com.zrb.mobile.ui.CircleImageView;
import com.zrb.mobile.ui.ObserveScrollView;
import com.zrb.mobile.ui.ObserveScrollView.OnScrollListener;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ViewUtil;
import com.zrb.mobile.utility.ZrbRestClient;
import com.zrb.mobile.utility.ZrbRestClient.HttpResponseListener;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class User_centerfragment extends Fragment implements OnClickListener,
		OnScrollListener {

//	private LoadUserAvatar avatarLoader;
	View RootView;
	ObserveScrollView myinfoView;
	TextView tvname, tvdept, tvpositon;
	View loginbtn, bottomLayout, logoview;

	TextView tvAttentionNum, tvAttentionProj, tvAttentionfund;
	// View investlayout,myproject;
	CircleImageView mavater;
	private String avatar = "";
	private String userName = "";
	private boolean hidden;
	private int loginstatus = -1;// 1 login ,2 logout,
	RelativeLayout titlebar;

	// iv_avatar
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// return inflater.inflate(R.layout.u_center_registerstep1, null);

		View view = inflater.inflate(R.layout.u_center_nologin, container,
				false);
		RootView = view;
		initView();
		return RootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
//		avatarLoader = new LoadUserAvatar(getActivity());
		// avatar = LocalUserInfo.getInstance(getActivity()).getUseravatar();
		userName = LocalUserInfo.getInstance(getActivity()).getUserName();

	}

	private void initView() {

		myinfoView = (ObserveScrollView) RootView.findViewById(R.id.myprofile);
		myinfoView.setOnScrollListener(this);

		mBgDrawable = this.getResources().getDrawable(R.drawable.app_bg2);

		titlebar = (RelativeLayout) RootView.findViewById(R.id.include1);
		titlebar.setBackgroundDrawable(mBgDrawable);

		tvname = (TextView) RootView.findViewById(R.id.tv_name);
		tvdept = (TextView) RootView.findViewById(R.id.tv_government);

		tvpositon = (TextView) RootView.findViewById(R.id.tv_user_dept);

		tvAttentionNum = (TextView) RootView
				.findViewById(R.id.tv_attention_number);
		tvAttentionProj = (TextView) RootView
				.findViewById(R.id.tv_attention_project);
		tvAttentionfund = (TextView) RootView
				.findViewById(R.id.tv_attention_fund);
		/*
		 * investlayout=RootView.findViewById(R.id.re_myattention);
		 * myproject=RootView.findViewById(R.id.re_myprojects);
		 */

		RootView.findViewById(R.id.re_myattention).setOnClickListener(this);
		RootView.findViewById(R.id.re_mypublish).setOnClickListener(this);
	/*	RootView.findViewById(R.id.re_myprojects).setOnClickListener(this);
		RootView.findViewById(R.id.re_moneyInvest).setOnClickListener(this);
		RootView.findViewById(R.id.re_mymessage).setOnClickListener(this);*/
		RootView.findViewById(R.id.re_authdes).setOnClickListener(this);
		RootView.findViewById(R.id.re_membership_service).setOnClickListener(this);

		loginbtn = RootView.findViewById(R.id.login_btn);
		loginbtn.setOnClickListener(this);
		mavater = (CircleImageView) RootView.findViewById(R.id.iv_avatar);
		mavater.setOnClickListener(this);

		bottomLayout = RootView.findViewById(R.id.bottom_layout);
		logoview = RootView.findViewById(R.id.imageView2);

		RootView.findViewById(R.id.txt_register).setOnClickListener(this);
		TextView titletxt = (TextView) RootView
				.findViewById(R.id.myhome_titleText);
		titletxt.setText("我的主页");
		ImageView rightimg = (ImageView) RootView
				.findViewById(R.id.myhome_right_icon);
		rightimg.setOnClickListener(this);
		// this.findViewById(R.id.register_up_sms_click).setOnClickListener(this);
		// this.findViewById(R.id.button_register).setOnClickListener(this);

	}

//	private void showUserAvatar(ImageView iamgeView, String avatar) {
//
//		if (TextUtils.isEmpty(avatar)) {
//			iamgeView.setImageResource(R.drawable.my_center_head);
//			return;
//		}
//		;
//		final String url_avatar = AppSetting.mediaServer + avatar;
//		iamgeView.setTag(url_avatar);
//		if (url_avatar != null && !url_avatar.equals("")) {
//			Bitmap bitmap = avatarLoader.loadImage(iamgeView, url_avatar,
//					new ImageDownloadedCallBack() {
//
//						@Override
//						public void onImageDownloaded(ImageView imageView,
//								Bitmap bitmap) {
//							if (imageView.getTag() == url_avatar) {
//								imageView.setImageBitmap(bitmap);
//							}
//						}
//					});
//			if (bitmap != null)
//				iamgeView.setImageBitmap(bitmap);
//
//		}
//	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		// Log.e("onHiddenChanged", "onHiddenChanged:"+hidden);
		// Toast.makeText(this.getActivity(), "onHiddenChanged:"+hidden,
		// Toast.LENGTH_SHORT).show();
		this.hidden = hidden;
		if (!hidden)
			showRelateview();
	}

	@Override
	public void onResume() {
		super.onResume();
		/*
		 * if(this.getUserVisibleHint()) showRelateview();
		 */
		if (!hidden)
			showRelateview();
	}

	// private int loginstatus=-1;//1 login ,2 logout,
	private void showRelateview() {
		// CommonUtil.showToast("showRelateview:", this.getActivity());
		boolean haslogined = AppSetting.curUser == null ? false : true;
		int curStatus = haslogined ? 1 : 2;

		if (haslogined) {

			tvname.setText(TextUtils.isEmpty(AppSetting.curUser.uname) ? ""
					: AppSetting.curUser.uname);
			tvdept.setText(TextUtils.isEmpty(AppSetting.curUser.org) ? ""
					: AppSetting.curUser.org);
			tvpositon.setText(TextUtils.isEmpty(AppSetting.curUser.industry) ? ""
					: AppSetting.curUser.industry + "·"
							+ AppSetting.curUser.position);

//			 tvAttentionNum.setText(TextUtils
//			 .isEmpty(AppSetting.curUser.collectedNumber + "") ? "0"
//			 : AppSetting.curUser.collectedNumber + "");
			 tvAttentionProj.setText(TextUtils
			 .isEmpty(AppSetting.curUser.collectProject + "") ? "0"
			 : AppSetting.curUser.collectProject + "");
			 tvAttentionfund.setText(TextUtils
			 .isEmpty(AppSetting.curUser.collectFund + "") ? "0"
			 : AppSetting.curUser.collectFund + "");

			// showUserAvatar(mavater, "");
			String vatar_temp = LocalUserInfo.getInstance(getActivity())
					.getUseravatar();

			if (!vatar_temp.equals(avatar)) {
				avatar = vatar_temp;
				ViewUtil.showUserAvatar(mavater, vatar_temp);
			}
			/*
			 * String name_temp =AppSetting.curUser.uname;//
			 * LocalUserInfo.getInstance(getActivity()).getUserName(); if
			 * (!name_temp.equals(userName)) { tvname.setText(name_temp);
			 * userName = name_temp; }
			 */
			// 得到关注数
			GetNumber();
		}
		if (curStatus == loginstatus)
			return;
		mBgDrawable.setAlpha(haslogined ? 0 : 255);
		loginstatus = curStatus;
		myinfoView.setVisibility(haslogined ? View.VISIBLE : View.GONE);

		bottomLayout.setVisibility(!haslogined ? View.VISIBLE : View.GONE);
		logoview.setVisibility(!haslogined ? View.VISIBLE : View.GONE);
		loginbtn.setVisibility(!haslogined ? View.VISIBLE : View.GONE);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.txt_register:
			UserRegister.launch(this.getActivity());
			break;
		case R.id.login_btn:
			// OnshowChanged();
			//User_phone_login.launch(this.getActivity(), true);
			Intent it2 = new Intent(this.getActivity(), User_phone_login.class);// Project_pubishmoneyActivity
			it2.putExtra("forResult", true);
			this.getActivity().startActivityForResult(it2, 234);
			break;
		case R.id.myhome_right_icon:
			// OnshowChanged();
			Intent it3 = new Intent(this.getActivity(), User_app_setting.class);
			startActivity(it3);
			break;
		case R.id.iv_avatar:
			Intent it4 = new Intent(this.getActivity(), User_my_baseInfo.class);
			startActivity(it4);
			break;
		case R.id.re_mypublish:
			Intent it5 = new Intent(this.getActivity(),User_my_collection.class);
			startActivity(it5);
			break;
		case R.id.re_myattention:
			Intent it11 = new Intent(this.getActivity(), User_my_attention.class);
			startActivity(it11);
			break;
	/*	case R.id.re_myprojects:
			Intent it6 = new Intent(this.getActivity(),
					User_my_ownprojects.class);
			startActivity(it6);
			break;

		case R.id.re_moneyInvest:
			Intent it7 = new Intent(this.getActivity(), User_my_findmoney.class);
			startActivity(it7);
			break;
		case R.id.re_mymessage:
			Intent it8 = new Intent(this.getActivity(), User_my_message.class);
			startActivity(it8);
			break;*/
		case R.id.re_authdes:
			Intent it6 = new Intent(this.getActivity(), User_my_dynamic.class);
			startActivity(it6);
			break;
		case R.id.re_membership_service:
			Intent it7 = new Intent(this.getActivity(), User_my_ownprojects.class);
			startActivity(it7);
			/*
			 * Intent it10 = new Intent(this.getActivity(),
			 * GuideActivity.class); startActivity(it10);
			 */
			break;
		}

	}

	private Drawable mBgDrawable;
	private int fadingHeight = 100; // 可隐藏的控件高度fadingHeight=300;
	private int oldY;
	private int fadingOffset;

	public static final int ALPHA_START = 0;
	public static final int ALPHA_END = 255;
	private static String TAG = "FadingScrollView";

	public void setActionBarAlpha(int alpha) throws Exception {
		if (titlebar == null || mBgDrawable == null) {
			throw new Exception(
					"acitonBar is not binding or bgDrawable is not set.");
		}
		mBgDrawable.setAlpha(alpha);
		titlebar.setBackgroundDrawable(mBgDrawable);
	}

	void updateActionBarAlpha(int alpha) {
		try {
			setActionBarAlpha(alpha);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onScroll(int scrollY) {
		// TODO Auto-generated method stub
		if (scrollY < fadingHeight)
			updateActionBarAlpha(scrollY * (ALPHA_END - ALPHA_START)
					/ fadingHeight + ALPHA_START);
	}

	ZrbRestClient mZrbRestClient;
	private void GetNumber() {
		RequestParams param = new RequestParams();
		param.put("zrb_front_ut", AppSetting.curUser.zrb_front_ut);
		CommonUtil.InfoLog("param", param.toString());

		if(mZrbRestClient==null){
			
			mZrbRestClient=new ZrbRestClient(this.getActivity());
			mZrbRestClient.setOnhttpResponseListener(new HttpResponseListener(){
				
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
					// initNotify(getActivity()
  					CommonUtil.InfoLog("ss",getActivity().getString(R.string.error_net_loadfail));
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					String results = new String(arg2);
					CommonUtil.InfoLog("TAG", results);
					try {
						Gson gson = new Gson();
						PersonNumberDto tmpDto = gson.fromJson(results, PersonNumberDto.class);
						if (tmpDto.res == 1) {

							tvAttentionNum.setText(TextUtils.isEmpty(AppSetting.curUser.collectedNumber + "") ? "0"
									: tmpDto.data.collectedNumber + "");
							tvAttentionProj.setText(TextUtils.isEmpty(AppSetting.curUser.collectProject+ "") ? "0"
									: tmpDto.data.collectProject + "");
							tvAttentionfund.setText(TextUtils.isEmpty(AppSetting.curUser.collectFund+ "") ? "0"
									: tmpDto.data.collectFund + "");
						}
					} catch (Exception e) {
						// initNotify(PushLiuYanActivity.this
						// .getString(R.string.error_serverdata_loadfail));
						CommonUtil.InfoLog("ss",getActivity().getString(R.string.error_serverdata_loadfail));
					}

				}
			});
		}
	   mZrbRestClient.post("userStatisticDetail/getStatisticNumber", param);
	}
}